﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Subgurim.Controles;
using ControlYSeguimiento.Domain;
using ControlYSeguimiento.Logging;
using System.IO;

namespace ControlYSeguimiento_Web_App.Monitoring
{
    public partial class Monitoring : System.Web.UI.Page
    {
        private Customer CurrentCustomer = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Form.Attributes.Add("enctype", "multipart/form-data");

          


            if (this.CheckAndLoadCustomer() == true)
            {
                PanelDetail.Visible = false;
                Panel panelLogBox = (Panel)Master.FindControl("PanelLogBox");
                panelLogBox.Visible = false;
                Panel panelNewUserBox = (Panel)Master.FindControl("PanelNewUserBox");
                panelNewUserBox.Visible = false;

                if (!IsPostBack)
                {
                    DdlLanguage.SelectedIndex = DdlLanguage.Items.IndexOf(DdlLanguage.Items.FindByValue(this.CurrentCustomer.RefreshMapTimer));
                    DdlLanguage.DataBind();
                }

                this.TimerRefresh.Interval = Convert.ToInt32(this.CurrentCustomer.RefreshMapTimer);
                this.Setup();
            }
            else
            {
                Response.Redirect("~/Default.aspx?msg=1");
            }
            if (Request.QueryString["id"] != null)
            {
                PanelDetail.Visible = true;
                Target targ = Facade.Instance.GetTargetById(Convert.ToInt32(Request.QueryString["id"]));
                LabelSelectedTarget.Text = targ.Name + " - Ultima actualización: " + targ.LastUpdateDateTime;
            }
        }

        private bool CheckAndLoadCustomer()
        {
            bool boolReturn = false;
            HttpCookie cookie = Request.Cookies["customerLogged"];
            if (cookie != null)
            {
#if DEBUG == false
                CurrentCustomer = Facade.Instance.GetCustomerByName(cookie["customerUserName"]);
#else
                CurrentCustomer = new Customer
                {
                    UserName = "lolo",
                    Surname = "Surname",
                    Password = "123456",
                    Name = "Name",
                    MapZoom = 10,
                    MapCoordinate = new Coordinate("-34.48894618571428", "-58.49734540000001"),
                    Mail = "mail",
                    Id = 1,
                    EnableAtFirstUse = false,
                    RefreshMapTimer = "30000",
                    Enable = true,
                    CustomerPlatform = new Platform { Id = 1 }

                };
#endif
                boolReturn = true;
            }
            return boolReturn;
        }

        #region Main Setup
        private void Setup()
        {
            this.SetupMonitoringMap();
            this.SetupCustomerTargets();
        }
        private void ResetMap()
        {
            GMap1.resetListeners();
            GMap1.reset();
        }
        private void SetupCustomerTargets()
        {
            Logger.Instance.Debug(this, "Centralizando mapa...");
            GMap1.setCenter(new GLatLng(CurrentCustomer.MapCoordinate.LatitudeDb, CurrentCustomer.MapCoordinate.LongitudeDb), CurrentCustomer.MapZoom);
            Logger.Instance.Debug(this, "Obteniendo blancos...");
#if DEBUG == false

            #region Obtencion de blancos
            foreach (Target target in Facade.Instance.GetTargetsFromCustomer(this.CurrentCustomer))
            {
                #region Mostrar Blanco en Mapa
                if (target.ShowInMap == true)
                {
                    GMarker marker;
                    Logger.Instance.Debug(this, "Tgt#" + target.Id.ToString() + "Lat=" + target.CurrentCooridinate.LatitudeDb.ToString() + " Long=" + target.CurrentCooridinate.LongitudeDb.ToString());
                    marker = new GMarker(new GLatLng(target.CurrentCooridinate.LatitudeDb, target.CurrentCooridinate.LongitudeDb));
                    Logger.Instance.Debug(this, "Tgt#" + target.Id.ToString() + " creando GIcon..");

                    GIcon objBaseIcon = new GIcon();
                    objBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
                    objBaseIcon.iconSize = new GSize(35, 38);
                    objBaseIcon.shadowSize = new GSize(37, 34);
                    objBaseIcon.iconAnchor = new GPoint(9, 34);
                    objBaseIcon.infoWindowAnchor = new GPoint(9, 2);
                    GIcon objIcon = new GIcon(objBaseIcon);
                    objIcon.image = "/Styles/Images/man.png";
                    GMarkerOptions objMarkerOptions = new GMarkerOptions(objIcon);
                    marker.options = objMarkerOptions;
                    GInfoWindow window = new GInfoWindow(marker, target.GetHtmlDescription());
                    Logger.Instance.Debug(this, "Tgt#" + target.Id.ToString() + " obteniendo ultimos trazos..");
                    GPolyline polygon = new GPolyline(this.TraceabilityLatLngList(Facade.Instance.GetTraceabilityByTarget(target)));
                    polygon.clickable = true;
                    GMap1.addPolyline(polygon);
                    //GListener listener = new GListener(polygon.PolylineID, GListener.Event.click, Trazabilidad.obtenerEventoClickHtml(objPolygon));
                    //GMap1.addListener(listener);
                    GMap1.addInfoWindow(window);
                }
                #endregion
            }
            #endregion
#else
            Target target = new Target
            {
                CurrentAltitude = "0",
                CurrentCooridinate = new Coordinate("-34.48894618571428", "-58.49734540000001"),
                CurrentCourse = "0",
                CurrentSpeed = "0",
                Customer = CurrentCustomer,
                Device = new Device { Enable = true, Id = 1, Imei = "12345648421812", Code="CYSXXXXXX" },
                Id = 1,
                Name = "Blanco",              
                Type = new TargetType("Person")
            };
            GMarker marker;
            Logger.Instance.Debug(this, "Tgt#" + target.Id.ToString() + "Lat=" + target.CurrentCooridinate.LatitudeDb.ToString() + " Long=" + target.CurrentCooridinate.LongitudeDb.ToString());
            marker = new GMarker(new GLatLng(target.CurrentCooridinate.LatitudeDb, target.CurrentCooridinate.LongitudeDb));
            Logger.Instance.Debug(this, "Tgt#" + target.Id.ToString() + " creando GIcon..");

            GIcon objBaseIcon = new GIcon();
            objBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            objBaseIcon.iconSize = new GSize(35, 38);
            objBaseIcon.shadowSize = new GSize(37, 34);
            objBaseIcon.iconAnchor = new GPoint(9, 34);
            objBaseIcon.infoWindowAnchor = new GPoint(9, 2);
            GIcon objIcon = new GIcon(objBaseIcon);
            objIcon.image = "/Styles/Images/man.png";
            GMarkerOptions objMarkerOptions = new GMarkerOptions(objIcon);
            marker.options = objMarkerOptions;
            GInfoWindow window = new GInfoWindow(marker, target.GetHtmlDescription());
#if DEBUG == false

            GPolyline polygon = new GPolyline(this.TraceabilityLatLngList(Facade.Instance.GetTraceabilityByTarget(target))); 
#else
            GPolyline polygon = new GPolyline();
#endif
            polygon.clickable = true;
            GMap1.addPolyline(polygon);
            //GListener listener = new GListener(polygon.PolylineID, GListener.Event.click, Trazabilidad.obtenerEventoClickHtml(objPolygon));
            //GMap1.addListener(listener);
            GMap1.addInfoWindow(window);

            //Trazabilidad objTrazaUltimosPasos = objConnection.obtenerCaminoCaballo(objCaballo, 10);
            //PolygonActionShow objPolygonAction = new PolygonActionShow();
            //objTrazaUltimosPasos.dibujarEn(GMap1, objPolygonAction);
#endif
        }
        private List<GLatLng> TraceabilityLatLngList(IEnumerable<Coordinate> coordinates)
        {
            List<GLatLng> points = new List<GLatLng>();
            if (coordinates != null)
            {
                foreach (Coordinate coordinate in coordinates)
                {
                    GLatLng point = new GLatLng(coordinate.LatitudeDb, coordinate.LongitudeDb);
                    points.Add(point);
                }
            }
            else
            {
                Logger.Instance.Warn(this, "No hubo movimientos en el último tiempo para este blanco");
            }
            return points;
        }
        public void SetupMonitoringMap()
        {
            Logger.Instance.Info(this, "Configurando mapa..");
            GMap1.addControl(new GControl(GControl.preBuilt.GOverviewMapControl));
            GMap1.addControl(new GControl(GControl.preBuilt.LargeMapControl));
            GMap1.mapType = GMapType.GTypes.Hybrid;
            GMap1.enableHookMouseWheelToZoom = true;
            GMap1.enableServerEvents = true;
        }
        #endregion Main Setup

        protected void TimerRefresh_Tick(object sender, EventArgs e)
        {
            CurrentCustomer.MapCoordinate.LatitudeDb = GMap1.GCenter.lat;
            CurrentCustomer.MapCoordinate.LongitudeDb = GMap1.GCenter.lng;
           

            Facade.Instance.SaveCustomer(CurrentCustomer);

            this.ResetMap();
            this.SetupMonitoringMap();
            this.SetupCustomerTargets();
        }
        protected string GMap1_ServerEvent(object s, GAjaxServerEventOtherArgs e)
        {
            return String.Empty;
        }
        protected void btnLogOut_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("customerLogged");
            cookie.Values.Add("customerUserName", CurrentCustomer.UserName);

            Transaction newTrans = new Transaction();
            newTrans.CustomerAssociated = CurrentCustomer;
            newTrans.Date = DateTime.Now;
            newTrans.TargetAssociated = null;
            newTrans.Type = TransactionType.UserLoggedOutType;
            newTrans.UserAssociated = null;
            newTrans.Value1 = newTrans.Value2 = newTrans.Value3 = newTrans.Value4 = newTrans.Value5 = newTrans.Value6 = null;
            newTrans.Result = "00";

            Facade.Instance.CreateTransaction(newTrans);


            cookie.Expires = DateTime.Now.AddHours(-3);
            Response.Cookies.Add(cookie);
            Response.Redirect("~/Default.aspx");
        }

        protected void ObjectDataSourceTargets_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = Facade.Instance;
        }

        protected void ObjectDataSourceTargets_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            HttpCookie cookie = Request.Cookies["customerLogged"];
            e.InputParameters[0] = cookie["customerUserName"];
        }

        protected void GridViewTargets_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (e.NewValues[2] != null)
            {
                e.NewValues[2] = new Coordinate(e.NewValues[2].ToString());
            }
        }

        protected void GridViewTargets_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "CentrarEnMapa":
                    Target targ = Facade.Instance.GetTargetById(Convert.ToInt32(e.CommandArgument));
                    targ.Customer = CurrentCustomer;
                    GMap1.setCenter(new GLatLng(targ.CurrentCooridinate.LatitudeDb, targ.CurrentCooridinate.LongitudeDb));
                    break;
            }

            CurrentCustomer.MapCoordinate.LatitudeDb = GMap1.GCenter.lat;
            CurrentCustomer.MapCoordinate.LongitudeDb = GMap1.GCenter.lng;
            Facade.Instance.SaveCustomer(CurrentCustomer);
        }

        protected void GridViewTargets_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            TimerRefresh_Tick(null, null);
        }

        protected string GMap1_MoveEnd(object s, GAjaxServerEventArgs e)
        {
            if (this.CheckAndLoadCustomer() == true)
            {
                this.CurrentCustomer.MapCoordinate.Latitude = e.center.lat.ToString().Replace('.', ',');
                this.CurrentCustomer.MapCoordinate.Longitude = e.center.lng.ToString().Replace('.', ',');
                this.CurrentCustomer.MapCoordinate.LatitudeDb = e.center.lat;
                this.CurrentCustomer.MapCoordinate.LongitudeDb = e.center.lng;
                this.CurrentCustomer.MapZoom = e.zoom;
                Facade.Instance.SaveCustomer(this.CurrentCustomer);
            }
            else
            {
                Response.Redirect("~/Default.aspx?msg=1");
            }

            return default(string);
        }

        protected void ObjectDataSourceTarget_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (Request.QueryString["id"] == null) { e.Cancel = true; }
            else { e.InputParameters[0] = Request.QueryString["id"]; }
        }

        protected void GridViewDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string picturePath = String.Empty;
            string pictureDbPath = String.Empty;

            FileUpload fileUpload = GridViewDetails.Rows[e.RowIndex].FindControl("FileUploadPicture") as FileUpload;
            if (fileUpload.HasFile == true)
            {
                string sign = @"/" + e.Keys[0] + e.Keys[1] + DateTime.Now.Ticks.ToString().PadLeft(16, '0');
                DirectoryInfo info = Directory.CreateDirectory(Server.MapPath(@"~/Monitoring/Users") + sign);
                picturePath = System.IO.Path.Combine(info.FullName, fileUpload.FileName);
                fileUpload.SaveAs(picturePath);
                pictureDbPath = @"Users" + sign + @"/" + fileUpload.FileName;
            }


            Device dev = Facade.Instance.GetDeviceById(Convert.ToInt32(e.Keys[0]));
            Target targ = Facade.Instance.GetTargetById(Convert.ToInt32(e.Keys[1]));
            dev.Imei = ((TextBox)(GridViewDetails.Rows[0].FindControl("TextBoxEditImei"))).Text;
            dev.Code = ((TextBox)(GridViewDetails.Rows[0].FindControl("TextBoxEditCode"))).Text;
            if (String.IsNullOrEmpty(pictureDbPath) == false) targ.Picture = pictureDbPath;
            targ.Device = dev;
            Facade.Instance.SaveTarget(targ);
            Facade.Instance.SaveDevice(dev);

        }


        protected void ObjectDataSourceTarget_Updating(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.Cancel = true;
        }

        protected void CustomValidatorEditImei_ServerValidate(object source, ServerValidateEventArgs args)
        {
            HiddenField hf = (HiddenField)GridViewDetails.Rows[0].FindControl("HiddenImei");
            if (hf.Value == args.Value) //Es el mismo IMEI
            {
                args.IsValid = true;
            }
            else if (Facade.Instance.ValidateImei(args.Value) == true) //Existe el IMEI ingresado???
            {
                args.IsValid = false;
            }
            else args.IsValid = true;
        }

        protected void CustomValidatorEditPicture_ServerValidate(object source, ServerValidateEventArgs args)
        {

        }

       

       
       
        protected void DdlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Logger.Instance.Info(this, "Modificar Timer de Refresco...");
            if (this.CheckAndLoadCustomer() == true)
            {
                this.CurrentCustomer.RefreshMapTimer = this.DdlLanguage.SelectedValue;
                Facade.Instance.SaveCustomer(this.CurrentCustomer);
                this.TimerRefresh.Interval = Convert.ToInt32(this.CurrentCustomer.RefreshMapTimer);
                Logger.Instance.Info(this, "Timer modificado OK en " + this.TimerRefresh.Interval.ToString());
            }
            else
            {
                Response.Redirect("~/Default.aspx?msg=1");
            }            
        }

    }


}